#ifndef __MODBUS_RTU_H__
#define __MODBUS_RTU_H__

#include "sys.h"
#include "usart.h"
#include "hcsr04.h"
#include "stm32f10x_usart.h"
#include "led.h"
#include <string.h>

// 是否开启调试
#define DEBUG 0

// 定义Modbus RTU缓冲区大小
#define MODBUS_BUFFER_SIZE 256
// 定义Modbus RTU寄存器的大小
#define MODBUS_REG_SIZE 64
// 接收到的从机地址
extern uint8_t slave_addr;
// 功能码
extern uint8_t funcation_code;
// 起始地址
extern uint16_t start_address;
// 读取数量
extern uint16_t count;
// 接收到的数据
extern uint8_t recv_data_buf[64];
// 接收到的字节数
extern uint8_t byte_count;
// CRC码
extern uint16_t check_code;
// CRC状态码
enum CHECK_STATUS
{
	CHECK_SUCC,
	CHECK_ERROR,
	SLAVE_ADDR_ERROR,
	FUNCATION_CODE_ERROR,
	SET_HEIGHT,
};

// 用于转换进制
union short_byte
{
	uint8_t b[2];
	uint16_t s;
};

// 读取寄存器数据
extern int modbus_read_reg(uint16_t start_addr, uint16_t length, uint8_t *dst_buf);
// 写入寄存器数据
extern int modbus_write_reg(uint16_t start_addr, uint16_t length, uint8_t *src_buf);
extern void Modbus_Read_Registers(uint16_t start, uint16_t count, uint8_t *buffer);
extern u16 Modbus_CRC16(uint8_t *data, int len);
extern uint8_t modbus_recv(uint8_t *buffer);
// 组包发送报文
extern void modbus_send(uint8_t slave_addr, uint8_t funcation_code, uint16_t start_addr, uint8_t data_len);
extern uint16_t check_CRC16(uint8_t *pucFrame, uint16_t usLen);

// 主机字节序(小端)转网络字节序(大端)
extern uint32_t htonl(uint32_t hostlong);
extern uint16_t htons(uint16_t hostshort);
// 网络字节序(大端)转主机字节序(小端)
extern uint32_t ntohl(uint32_t netlong);
extern uint16_t ntohs(uint16_t netshort);

#endif
